//
//  x.swift
//  SlaughterClient
//
//  Created by Zhouweibin on 2018/1/27.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

class SignBaseVC: UIViewController {

   let locationManager = CLLocationManager()
   
  
   var signType:SignType = .go2work {
       didSet {
           switch signType {
           case .go2work:
               qdButton.isSelected = true
               submitButton.isSelected = false
               businessButton.isSelected = false
           case .visit:
               qdButton.isSelected = false
               submitButton.isSelected = true
               businessButton.isSelected = false
           case .business:
               qdButton.isSelected = false
               submitButton.isSelected = false
               businessButton.isSelected = true
           default:
               break
           }
       }
   }
   var selectPhotos = [UIImage]()
    var attendanceModel = Attendance(json: "")
    var requiredLoArr = [AddrUploadModel]()
   

   var marktf: PlaceHolderTextView = {
       let textView = PlaceHolderTextView()
       textView.placeHolder = "请填写签到备注"
       textView.layer.borderWidth = 1
       textView.layer.borderColor = UIColor.lightGray.cgColor
       textView.layer.cornerRadius = 4
       textView.backgroundColor = UIColor.white
       textView.font = UIFont.systemFont(ofSize: 16)
       return textView
   }()
 
   
   var imgUtil:KSImageSelectUtil!
   
   var signInfoView: SignInfoView = {
       let view = SignInfoView()
       return view
   }()
   var acBg: UIView = {
       let view = UIView()
       view.backgroundColor = .white
       view.layer.cornerRadius = 8
        return view
   }()
   var bottomBg: UIView = {
       let view = UIView()
       view.backgroundColor = .white
       
       return view
   }()
   lazy var qdButton: ZyaSignButton = {
       let button = ZyaSignButton()
   
       button.setTitle("打卡", for: .normal)
       button.setImage(UIImage(named: "si_dk_d"), for: .normal)
       button.setImage(UIImage(named: "si_dk_l"), for: .selected)
       button.setTitleColor(.lightGray, for: .normal)
       button.setTitleColor(Theme.primaryColor(), for: .selected)

       return button
   } ()
   
   var submitButton: ZyaSignButton = {
       let button = ZyaSignButton()
       button.setTitle("拜访", for: .normal)
       button.setImage(UIImage(named: "si_bf_d"), for: .normal)
       button.setImage(UIImage(named: "si_bf_l"), for: .selected)
       button.setTitleColor(.lightGray, for: .normal)
       button.setTitleColor(Theme.primaryColor(), for: .selected)

       return button
   }()
   
   lazy var businessButton: ZyaSignButton = {
       let button = ZyaSignButton()
       button.setTitle("出差", for: .normal)
       button.setImage(UIImage(named: "si_cc_d"), for: .normal)
       button.setImage(UIImage(named: "si_cc_l"), for: .selected)
       button.setTitleColor(.lightGray, for: .normal)
       button.setTitleColor(Theme.primaryColor(), for: .selected)
       return button
   } ()
   var signHeight:CGFloat = 130
   var signRoundButton: UIButton = {
       let v = UIButton()
       v.layer.cornerRadius = 65
       v.backgroundColor = Theme.primaryColor()
       v.setTitle("签到", for: .normal)
       v.setTitleColor(.white, for: .normal)
       v.titleLabel?.numberOfLines = 2
       v.titleLabel?.textAlignment = .center
        return v
   }()
  

   
   lazy var weanLabel: UILabel = {
       let label :UILabel = UILabel()
       label.text = "使用上班签到、下班签退需将设置中的APP位置设置为始终"
       label.numberOfLines = 0
       label.font = UIFont.systemFont(ofSize: 12)
       label.textColor = UIColor.lightGray
       return label
   } ()

    private let baiduMapManager = BaseBaiduMapHandler()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if isBaiduMapPlatform() {
            baiduMapManager.startLocation()
            baiduMapManager.update = { [unowned self] coor, addr in
                self.latitude = "\(coor.latitude)"
                self.longitude = "\(coor.longitude)"
                self.addressInfo = addr
            }
        } else {
            BaseGaodeMapHandler.shared.update = { [weak self] in
                self?.updateLocation()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if isBaiduMapPlatform() {
            baiduMapManager.stopLocation()
            baiduMapManager.update = nil
        } else {
            BaseGaodeMapHandler.shared.update = nil
        }
    }
    
   // MARK: left cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏背景颜色为透明
        
        self.signType = .go2work
        
        var mapView: UIView
        
        if isBaiduMapPlatform() {
            mapView = baiduMapManager.getMapView(zoomLevel: 17, showsUserLocation: true, frame: view.bounds)
        } else {
            mapView = BaseGaodeMapHandler.shared.getMapView(reInit: true, zoomLevel: 13, showsUserLocation: true)
        }
        
        updateLocation()
        
        title = "签到"
        
        
        
        let imageView = UIImageView(image: UIImage(named: "sign_detail")!.withRenderingMode(.alwaysOriginal))
        imageView.contentMode = .scaleAspectFit // 或 .scaleAspectFill，根据你的需要
        imageView.frame = CGRect(x: 0, y: 0, width: 26, height: 26)
        
        let button = UIButton(type: .system)
        button.addSubview(imageView)
        button.contentHorizontalAlignment = .center
        button.contentVerticalAlignment = .center
        button.frame = CGRect(origin: .zero, size: imageView.frame.size)
        button.addTouchUpInSideAction { _ in
            self.signDetail()
        }
        let barButtonItem = UIBarButtonItem(customView: button)
        
        
        
        
        navigationItem.rightBarButtonItem = barButtonItem
        edgesForExtendedLayout = UIRectEdge()
        view.backgroundColor = Theme.TABLEVIEW_COLOR
        
        view.addSubview(mapView)
        mapView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        view.addSubview(acBg)
        acBg.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(250)
        }
        
        
        let xMarg:CGFloat = 8
        signInfoView.frame = CGRect(x:0,y:8,width:KSGlobal.screenW,height:43)
        acBg.addSubview(signInfoView)
        acBg.addSubview(marktf)
        marktf.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            
            make.top.equalTo(signInfoView.snp.bottom).offset(8)
            
            make.height.equalTo(70)
        }
        imgUtil = KSImageSelectUtil(frame: CGRect(x:xMarg,y:marktf.frame.maxY,width:KSGlobal.screenW - 20 - xMarg * 2,height:80),httpHeader: USERINFO.picUrl.unwrap,maxImgCount: 5,numberOfRow: 5,picType: [.takePicture],viewType:.editable)
        imgUtil.ksDelegate = self
        acBg.addSubview(imgUtil)
        imgUtil.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(xMarg)
            make.right.equalToSuperview().offset(-xMarg)
            
            make.top.equalTo(marktf.snp.bottom).offset(8)
            
            make.height.equalTo(80)
        }
        
        acBg.addSubview(weanLabel)
        weanLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(xMarg)
            
            make.top.equalTo(imgUtil.snp.bottom)
            
        }
        
        view.addSubview(signRoundButton)
        view.addSubview(bottomBg)
        signRoundButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(signHeight)
            make.bottom.equalTo(bottomBg.snp.top).offset(-20)
        }
        
        
        bottomBg.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(80)
        }
        
        bottomBg.addSubview(qdButton)
        
        bottomBg.addSubview(submitButton)
        
        bottomBg.addSubview(businessButton)
        qdButton.addTouchUpInSideAction { _ in
            self.signType = .go2work
        }
        submitButton.addTouchUpInSideAction { _ in
            self.signType = .visit
        }
        businessButton.addTouchUpInSideAction { _ in
            self.signType = .business
        }
        qdButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(30)
            make.width.height.equalTo(50)
            make.centerY.equalToSuperview().offset(-8)
        }
        submitButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(50)
            make.centerY.equalToSuperview().offset(-8)
        }
        businessButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-30)
            make.width.height.equalTo(50)
            make.centerY.equalToSuperview().offset(-8)
        }
        
        //       qdButton.addTarget(self, action: #selector(authorityCheck), for: .touchUpInside)
        //       submitButton.addTarget(self, action: #selector(submitHandle), for: .touchUpInside)
        //       businessButton.addTarget(self, action: #selector(businessAction), for: .touchUpInside)
        
        
        lastInfo()
        signRoundButton.addTouchUpInSideAction { _ in
            switch self.signType {
                case .go2work:
                    self.authorityCheck()
                case .visit:
                    self.submitAction()
                case .business:
                    self.businessAction()
                default:
                    break
            }
        }
        
        
        self.getSignLocation()
         
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if isBaiduMapPlatform() {
            baiduMapManager.startLocation()
            
        } else {
            BaseGaodeMapHandler.shared.update = { [weak self] in
                self?.updateLocation()
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(clearLocation), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(updateLocation), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        if isBaiduMapPlatform() {
            baiduMapManager.stopLocation()
            baiduMapManager.update = nil
        } else {
            BaseGaodeMapHandler.shared.update = nil
        }
        
        NotificationCenter.default.removeObserver(self)
    }
    
    // 清空定位信息
    @objc private func clearLocation() {
        self.latitude = ""
        self.longitude = ""
        self.addressInfo = ""
        if isBaiduMapPlatform() {
            
        } else {
            BaseGaodeMapHandler.shared.setCenterCoordinate(CLLocationCoordinate2D())
        }
    }
    
    // 重新定位
    @objc private func updateLocation() {
        let loOri = LocationTool.shared.getlocInfo { locNew in
            self.latitude = "\(locNew.coor.latitude)"
            self.longitude = "\(locNew.coor.longitude)"
            self.addressInfo = locNew.address
            if isBaiduMapPlatform() {
                self.baiduMapManager.setCenterCoordinate(locNew.coor)
            } else {
                BaseGaodeMapHandler.shared.setCenterCoordinate(locNew.coor)
            }
        }
        self.latitude = "\(loOri.coor.latitude)"
        self.longitude = "\(loOri.coor.longitude)"
        self.addressInfo = loOri.address
        if isBaiduMapPlatform() {
            baiduMapManager.setCenterCoordinate(loOri.coor)
        } else {
            BaseGaodeMapHandler.shared.setCenterCoordinate(loOri.coor)
        }
    }
    
    func getSignLocation() {
        // 获取签到地点
        KSNetwork.shared.doRequest(API.queryStartAttendancePlace(org_code: USERINFO.orgCode.unwrap)) { (data:BaseResult<AddrUploadModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    self.requiredLoArr = infos
                    if isBaiduMapPlatform() {
                        var sLocas = [BMKPointAnnotation]()
                        var overlays: Array<BMKCircle> = Array()
                        for item in infos {
                            let sl2 = BMKPointAnnotation()
                            let lat2 = doubleTran(item.pLatitude)
                            let lon2 = doubleTran(item.pLongitude)
                            let coor = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
                            sl2.coordinate = coor
                            sl2.title = item.pAttendancePlace
                            sLocas.append(sl2)
                            
                            let circle: BMKCircle = BMKCircle(center: coor, radius: doubleTran(item.pAttendanceDistance))!
                            overlays.append(circle)
                            
                            
                        }
                        self.baiduMapManager.addOverlays(overlays)
                        self.baiduMapManager.addAnnotations(sLocas)
                        
                    } else {
                        var sLocas = [MAPointAnnotation]()
                        var overlays: Array<MACircle> = Array()
                        for item in infos {
                            let sl2 = MAPointAnnotation()
                            let lat2 = doubleTran(item.pLatitude)
                            let lon2 = doubleTran(item.pLongitude)
                            let coor = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
                            sl2.coordinate = coor
                            sl2.title = item.pAttendancePlace
                            sLocas.append(sl2)
                            
                            let circle: MACircle = MACircle(center: coor, radius: doubleTran(item.pAttendanceDistance))!
                            overlays.append(circle)
                            
                            
                        }
                        
                        BaseGaodeMapHandler.shared.addOverlays(overlays)
                        BaseGaodeMapHandler.shared.addAnnotations(sLocas)
                    }

                }
            } else {
                
            }
        }
    }
   
  
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
    }
  

    func lastInfo() {
        
        KSNetwork.shared.doRequest4Sj(API.querySignHistory(date: Date.today)) {[weak self] (data:SwResult<SignHistory>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infos {
                    let qdArr = infos.filter { $0.zType ==  SignType.go2work.rawValue }
                    let qtArr = infos.filter { $0.zType ==  SignType.afterWork.rawValue }
                    
                    self.attendanceModel.isCheckedOut = (qtArr.count > 0)
                    self.attendanceModel.isCheckedIn = (qdArr.count > 0)
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
   
    @objc private func queryWorkTrack() {
        let vc = WorkTrackController()
        vc.selectPeopleButton.isHidden = true
        vc.param.entityName = USERINFO.staffId!
        vc.username = USERINFO.staffNm!
        vc.title = "\(USERINFO.staffNm!)的轨迹 "
        navigationController?.pushViewController(vc, animated: true)
    }
   
    // MARK: private method
    @objc private func signDetail() {
        let vc = SignDetailViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
   
    // 权限检查
    @objc private func authorityCheck() {
        
        // 1. 還沒有詢問過用戶以獲得權限
        if CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        }
        // 2. 用戶不同意
        else if CLLocationManager.authorizationStatus() == .denied {
            alertShow()
        }
        // 3. 用戶已經同意
        else if CLLocationManager.authorizationStatus() == .authorizedAlways {
            self.qdAction()
            
            
        } else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            
            self.qdAction()
        }
    }
   
   
    func alertShow() {
        let alert = UIAlertController(title: "上班签到需要开启后台定位", message: "请进入系统【设置】>【隐私】>【定位服务】中打开开关，并允许本应用【使用期间】使用定位服务", preferredStyle: .alert)
        
        let gotoAction = UIAlertAction(title: "前往设置", style: .default) { (_) in
            // 开启权限
            let url = URL(string: UIApplication.openSettingsURLString)
            if let anUrl = url {
                if UIApplication.shared.canOpenURL(anUrl) {
                    if let anUrl = url {
                        UIApplication.shared.open(anUrl, options: [:], completionHandler: { result in
                        })
                    }
                }
            }
        }
        
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(gotoAction)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
   

    func joinSignDic() -> [String:Any] {
        var data = [String: Any]()
        let uuid = fetchDeciveIdentifier()
        data.updateValue(USERINFO.cUnitnameIdHs!, forKey: "s_qd_org_id")
        data.updateValue(USERINFO.cUnitnameHs!, forKey: "s_qd_org_nm")
        data.updateValue(USERINFO.staffId!, forKey: "s_qd_staff_id")
        data.updateValue(USERINFO.staffNm!, forKey: "s_qd_staff_nm")
        data.updateValue(Date.nowTimeToMinute, forKey: "s_qd_date")
        data.updateValue(addressInfo, forKey: "s_qd_place")
        data.updateValue(marktf.text.filterQuote, forKey: "s_qd_remark")
        data.updateValue(latitude, forKey: "s_latitude")
        data.updateValue(longitude, forKey: "s_longitude")
        data.updateValue(uuid, forKey: "s_pid")
        data.updateValue("IOS", forKey: "s_phone_type")
        if signType == .go2work {
            // 现在都是签到，所有用 12点判断签到和签退逻辑
            let clock12 = Date.today + " 12:00:00"
            let tmC = Date.timeComparison(aStr: Date.nowTimeToSecond, bStr: clock12).intWrap

            if tmC > 0 {
                data.updateValue("3", forKey: "z_type")

            } else {
                data.updateValue("1", forKey: "z_type")
            }
           
        } else {
            data.updateValue(signType.rawValue, forKey: "z_type")

        }
        return data
    }
   
    // 上次位置信息
    private func loadLoactionInfo(marketModel:MarketSuveyModel? = nil,complmentHandler: (() -> Void)?) {
        
        guard self.latitude != "" && self.longitude != "" && self.addressInfo != "" else {
            KSToast("位置获取未成功，请退出重新进入并稍作等待")
            return
        }
        
        var data = joinSignDic()
        
        if signType == .survey {
            
            let detaildic = marketModel!.dictionaryRepresentation()
            data.updateValue(detaildic, forKey: "detail")
        }
        let json = dictionaryToJson(data)
        
        if signType == .go2work || signType == .afterWork {
            if judgeSignAvalible()  {
                signNetwork(json:json,complmentHandler:complmentHandler)
            }  else {
                alertUtil(self, title: "当前不再考勤范围，是否继续签到（注：联系人事维护考勤范围）", operateS: [nameAction(name: "确定", action: { _ in
                    self.signNetwork(json:json,complmentHandler:complmentHandler)
                })])
            }
        } else {
            signNetwork(json:json,complmentHandler:complmentHandler)
        }
    }
    
    func signNetwork(json:String,complmentHandler: (() -> Void)?) {
        var api:API?
        let imageStr = imageToBase64EncodedString(images: selectPhotos)
        
        api = API.saveSign(data: json, pictrueByte: imageStr,imgs: selectPhotos)
        KSNetwork.shared.doRequest(api!) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                if let handler = complmentHandler {
                    handler()
                }
            } else {
                
                if let info = data.errorCombine, info.contains("绑定") {
                    BindHelper.shared.bindPhone(sms_type: "1")
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
                
            }
        }
    }
   
   
    func judgeSignAvalible () -> Bool {
        if requiredLoArr.count > 0 {
            
            var avalible = false
            for item in self.requiredLoArr {
                
                let dic = getDistance(lat1: doubleTran(latitude), lng1: doubleTran(longitude), lat2: doubleTran(item.pLatitude), lng2: doubleTran(item.pLongitude))
                
                if dic <= doubleTran(item.pAttendanceDistance) {
                    avalible = true
                }
            }
            
            return avalible
            
        } else {
            return true
        }
    }
    
    @objc private func qdAction() {
 
        signType = .go2work
        
        alertUtil(self, title: "是否确定打卡", operateS: [nameAction(name: "确定", action: { [unowned self]  (_) in
            
            self.loadLoactionInfo {
                
#if targetEnvironment(simulator)
                // your simulator code
#else
                // your real device code
                
                KSToast("签到成功")
                
                self.imgUtil.dataArray.removeAll()
                self.imgUtil.reloadData()
                self.selectPhotos.removeAll()
                self.marktf.text = ""
                
                self.attendanceModel.isCheckedOut = false
                self.attendanceModel.isCheckedIn = true
                
                // 记录本次收集轨迹人员信息
                entityName = USERINFO.staffId.unwrap
                
                self.navigationController?.popViewController(animated: true)
#endif
            }
        })])
     
    }
    
    @objc private func submitAction() {
        signType = .visit
        loadLoactionInfo {
            KSToast("拜访签到成功")
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc private func businessAction() {

        signType = .business
        loadLoactionInfo {
            KSToast("出差签到成功")
            self.navigationController?.popViewController(animated: true)
        }
    }

    
   var longitude = ""
   var latitude = ""
    
   var addressInfo: String = "" {
       didSet {
           signInfoView.addressLabel.text = addressInfo
           signInfoView.dateLabel.text = Date.nowTimeToMinute
       }
   }

}




extension SignBaseVC: CLLocationManagerDelegate {
   
   func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
       self.presentedViewController?.dismiss(animated: false, completion: nil)
   }
}

extension SignBaseVC:KSImageUtilDelegate {
   
   func dealBeforeAddImages(_ util: KSImageSelectUtil, imgs: [UIImage]) -> [UIImage] {
       let imgs_marked = imgs.compactMap { UIImage.getWaterMark($0, title: Date.nowTimeToSecond, andMark: UIFont.systemFont(ofSize: 140), andMark: .red) }
       return imgs_marked
   }
   
   
   func addImages(_ util: KSImageSelectUtil, imgs: [UIImage]) {
       selectPhotos += imgs
   }
   
   func deleteImage(_ util: KSImageSelectUtil, index: Int) {
       selectPhotos.remove(at: index)
       self.imgUtil.deleteLocalImg(tag: index)
   }
}



class ZyaSignButton:UIButton {
   override init(frame: CGRect) {
       super.init(frame: frame)
       self.titleLabel?.textAlignment = .center
       self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
   }
   
   required init?(coder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
   override func layoutSubviews() {
       super.layoutSubviews()
       let w = self.frame.width
       let h = self.frame.height
       self.imageView?.frame = CGRect(x: w * 0.25, y: 0, width: w * 0.5, height: h/2)
       self.titleLabel?.frame = CGRect(x: 0, y: h/2, width: w, height: h/2)
   }
}


open class SignPictrue: SwiftyJSONAble {

    // MARK: Declaration for string constants to be used to decode and also serialize.
    fileprivate let kPictrueSPicUrlKey: String =  "s_pic_url"
    fileprivate let kPictrueIdKeyKey: String = "id_key"
    fileprivate let kPictrueSPicTypeKey: String = "s_pic_type"
    fileprivate let kVouId:String =   "vou_id"
    fileprivate let ksPicByte:String = "s_pic_byte"

    // MARK: Properties
    open var sPicUrl: String?
    open var idKey: String?
    open var sPicType: String?
    open var sPicByte: String?
    open var vouId: String?
    open var image:UIImage?
    // MARK: SwiftyJSON Initalizers
    /**
    Initates the instance based on the object
    - parameter object: The object of either Dictionary or Array kind that was passed.
    - returns: An initalized instance of the class.
    */
    convenience public init(object: Any) {
        self.init(json: JSON(object))
    }

    /**
    Initates the instance based on the JSON that was passed.
    - parameter json: JSON object from SwiftyJSON.
    - returns: An initalized instance of the class.
    */
    public required init(json: JSON) {
        sPicUrl = json[kPictrueSPicUrlKey].string
        idKey = json[kPictrueIdKeyKey].int.isSome ? json[kPictrueIdKeyKey].int.unwrap : json[kPictrueIdKeyKey].string
        vouId = json[kVouId].int.isSome ? json[kVouId].int.unwrap : json[kVouId].string
        sPicType = json[kPictrueSPicTypeKey].stringValue
        sPicByte = json[ksPicByte].stringValue
    }

    /**
    Generates description of the object in the form of a NSDictionary.
    - returns: A Key value pair containing all valid values in the object.
    */
    open func dictionaryRepresentation() -> [String: Any] {
        var dictionary: [String: Any] = [:]
        if let value = sPicUrl { dictionary[kPictrueSPicUrlKey] = value }
        if let value = idKey { dictionary[kPictrueIdKeyKey] = value } else {
            dictionary[kPictrueIdKeyKey] = ""
        }
        if let value = sPicType { dictionary[kPictrueSPicTypeKey] = value }
        if let value = vouId { dictionary[kVouId] = value } else {
            dictionary[kVouId] = ""
        }
        if let value = sPicByte { dictionary[ksPicByte] = value }
        return dictionary
    }

}
